﻿using System;
using System.Collections.Generic;

namespace N2.Json.Converters
{
	using Newtonsoft.Json;
	
	/// <summary>
	/// Used to render ContentItem.Children property as an array of stubs.
	/// </summary>
	class JsonChildrenCollectionConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			return typeof(IList<ContentItem>).IsAssignableFrom(objectType);
		}
		//TODO implement deserialization
		public override object ReadJson(JsonReader reader, Type objectType)
		{
			throw new NotImplementedException();
		}

		public override void WriteJson(JsonWriter writer, object value)
		{
			writer.WriteStartArray();
			var _list = value as IList<ContentItem>;

			if (null != _list) {
				//HACK access Parent via first child
				if (_list.Count > 0) {
					var _owner = _list[0].Parent;
					//re-get children via method,
					// this will inquire access check implicitly
					_list = _owner.GetChildren();
					WriteItems(writer, _list);
				}
				
				//WriteItems(writer, _list);
			}

			writer.WriteEndArray();
		}

		static void WriteItems(JsonWriter writer, IEnumerable<ContentItem> items)
		{
			var _ciConverter = new JsonContentItemProxyConverter();
				
			foreach (var _item in items) {
				_ciConverter.WriteJson(writer, _item);
			}
		}
	}
}
